#include "ParseXML.h"
#include <iostream>
#include <xercesc\sax\HandlerBase.hpp>
#include <xercesc\parsers\SAXParser.hpp>
#include "CustomSAXHandler.h"

using namespace std;
using namespace xercesc;

ParseXML::ParseXML(void)
{
}

ParseXML::~ParseXML(void)
{
}

void ParseXML::run(void)
{
    try
	{
        XMLPlatformUtils::Initialize();
    }
    catch (const XMLException& xmle)
	{
        char* message = XMLString::transcode(xmle.getMessage());
        cout << "Error during initialization:\n" << message << "\n";
        XMLString::release(&message);
    }

	char* dir;
	if((dir = _getcwd(NULL, 0)) == NULL)
	{
		cout << "Unable to get the current directory...\n";
	}
	else
	{
		string currentDirectory(dir);
		currentDirectory.append("\\").append("parsexml_sample_sax.xml");
		delete dir;

		char dir[256];
		ifstream file;
		file.exceptions(ifstream::failbit | ifstream::badbit);
		try
		{
			file.open(currentDirectory);
			file.close();
		}
		catch (ifstream::failure e)
		{
			cout << "Unable to open file." << endl;
			cout << "Enter the path to the directory containing the xml file: ";
			cin >> dir;
			currentDirectory.assign(dir).append("parsexml_sample_sax.xml");
		}

		SAXParser* parser = new SAXParser();
		parser->setDoNamespaces(true);
		CustomSAXHandler* docHandler = new CustomSAXHandler();
		ErrorHandler* errHandler = (ErrorHandler*) docHandler;
		parser->setDocumentHandler(docHandler);
		parser->setErrorHandler(errHandler);
		
		try
		{
			parser->parse(currentDirectory.c_str());
		}
		catch (const XMLException& xmle)
		{
			char* message = XMLString::transcode(xmle.getMessage());
			cout << "Exception message is: \n" << message << ".\n";
			XMLString::release(&message);
		}
		catch (const SAXParseException& toCatch)
		{
			char* message = XMLString::transcode(toCatch.getMessage());
			cout << "Exception message is: \n" << message << "\n";
			XMLString::release(&message);
		}
		catch (...)
		{
			cout << "Unexpected Exception \n";
		}
		
		delete parser;
		delete docHandler;
	}
}
